package com.xiao.security;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @_PackageName:com.xiao.security
 * @_ClassName:MySecurity
 * @_Description:
 * @_Author：笑老二
 * @_data 2020/12/09 13:01
 */

@EnableWebSecurity
public class MySecurity extends WebSecurityConfigurerAdapter {


    /**
     * 首页所有人可以访问
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/main").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        /**
         * 没有权限会自动太转到login界面
         * 自定义登录界面 loginPage(url)
         * 登入成功界面 loginProcessingUrl(url)
         */
        http.formLogin().loginPage("/toLogin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login");

        /**
         * 注销页面
         * http.authorizeRequests().antMatchers(&quot;/**&quot;).hasRole(&quot;USER&quot;).and().formLogin()
         * 				.and()
         * 			// sample logout customization
         * 			.logout().deleteCookies(&quot;remove&quot;).invalidateHttpSession(false)
         * 			.logoutUrl(&quot;/custom-logout&quot;).logoutSuccessUrl(&quot;/logout-success&quot;);
         *
         *
         * 		注销返回的登录界面---默认在跳转到自带页面(logout)
         */
        http.logout().logoutSuccessUrl("/");

        /**
         * 设置记住功能
         * 设置绑定的前端界面记住功能按钮name :rememberMeParameter()
         */
        http.rememberMe().rememberMeParameter("remember");

    }

    /**
     * 认证
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
                .and()
                .withUser("xiao").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }

}
